package cn.jcby.app.lebu.service.impl;

import cn.jcby.app.lebu.controller.req.BasicListReq;
import cn.jcby.app.lebu.controller.res.DictRes;
import cn.jcby.app.lebu.dao.DictDao;
import cn.jcby.app.lebu.entity.DictEntity;
import cn.jcby.app.lebu.service.DictService;
import cn.jcby.app.lebu.utils.PageUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("dictService")
public class DictServiceImpl extends ServiceImpl<DictDao, DictEntity> implements DictService {

    @Autowired
    private DictDao dictDao ;
    @Override
    public PageUtils queryPage(BasicListReq params) {
        IPage<DictEntity> page = this.page(
                new Page<>(params.getPage(),params.getLimit()),
                Wrappers.<DictEntity>lambdaQuery()
        );

        return new PageUtils(page);
    }
    @Override
    public void add(DictEntity dictReq){
        DictEntity dict = new DictEntity() ;
        save(dict) ;
    }

    @Override
    public void updateBy(DictEntity dictReq){
        DictEntity dict = new DictEntity() ;
        updateById(dict) ;
    }

    @Override
    public List<DictRes> listByParentCode(String parentCode) {
        List<DictEntity> dictList = cacheListByParentCode(parentCode);
        return dictList
                .stream().map(dict -> {
            DictRes dictRes = new DictRes() ;
            BeanUtils.copyProperties(dict,dictRes) ;
            return dictRes ;
        }).collect(java.util.stream.Collectors.toList()) ;
    }

    @Override
    //@Cacheable(key = "'parentCode:'+#parentCode",cacheNames = {"dict"})
    public List<DictEntity> cacheListByParentCode(String parentCode) {
        return this.list(Wrappers.<DictEntity>lambdaQuery().eq(DictEntity::getParentCode,parentCode));
    }

    @Override
    public String getTagNameByCode(String parentCode, String occupation1) {
        List<DictEntity> list = cacheListByParentCode(parentCode);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.stream().filter(dict -> dict.getCode().equals(occupation1)).findFirst().orElse(new DictEntity()).getName();
        }
        return null;
    }

    @Override
    public DictEntity getDictByCode(String parentCode, String code) {
        List<DictEntity> list = cacheListByParentCode(parentCode);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.stream().filter(dict -> dict.getCode().equals(code)).findFirst().orElse(new DictEntity());
        }
        return null;
    }
}